package com.company;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

//启动类
public class MyTomcat {
    //默认端口
    private int port = 9000;
    private Map<String,String> urlServletMap=new HashMap<>();

    public MyTomcat(int port){
        this.port=port;
    }

    public void start() {

        //初始化URL和与之对应的servlet的关系
        initServeletMapping();
        //服务端用于监听的套接字
        ServerSocket serverSocket=null;
        try{
            serverSocket = new ServerSocket(port);
            System.out.println("MyTomcat is start...");

            while(true)
            {
                //受理客户端连接请求
                Socket socket=serverSocket.accept();
                InputStream inputStream=socket.getInputStream();
                OutputStream outputStream=socket.getOutputStream();

                MyRequest myRequest=new MyRequest(inputStream);
                MyResponse myResponse=new MyResponse(outputStream);


                if(myRequest.getUrl().equalsIgnoreCase("/favicon.ico"))
                    continue;

                //请求分发
                dispatch(myRequest,myResponse);

                socket.close();
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(serverSocket!=null)
            {
                try{
                    serverSocket.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    private void initServeletMapping(){
        //将每个URL和Servlet的映射关系存入 urlServletMap
        for(ServletMapping servletMapping : ServletMappingConfig.servletMappingList){
            urlServletMap.put(servletMapping.getUrl(),servletMapping.getClazz());
        }
    }

    private void dispatch(MyRequest myRequest,MyResponse myResponse)
    {
        //通过请求中的URL映射得到对应的Servlet类
        String clazz=urlServletMap.get(myRequest.getUrl());

        //System.out.println(clazz);

        //通过反射 得到对应Servlet的类类型
        //并通过类类型 创建该Servlet类的实例
        //这里既然通过映射关系 确定了Servlet类 为什么还要通过反射创建Servlet实例
        //一种代理模式
        try{
            Class <MyServlet> myServletClass = ( Class<MyServlet> ) Class.forName(clazz);
            MyServlet myServlet= myServletClass.newInstance();

            myServlet.service(myRequest,myResponse);

        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        new MyTomcat(9000).start();
    }
}
